//
//  LoginViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/7/10.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//  

import UIKit

class LoginViewController: BaseViewController {
    
    @IBOutlet weak var accountField: UITextField!
    
    @IBOutlet weak var passField: UITextField!
    
    @IBAction func loginAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.load(with: "login")
    }
    
    override var names: Array<String> {
        get{
            return ["login","userinfo"]
        }
    }
    
    override func path(for name: String) -> String {
        if name == "login" {
            return Login
        } else {
            return GetUserInfo
        }
    }
    
    override func param(for name: String) -> Dictionary<String, Any> {
        if name == "login" {
            return ["account":self.accountField.text!,"password":self.passField.text!,"deviceNumber": User.uuid]
        } else {
            return [:]
        }
    }
    
    override func strategy(for name: String) -> (Bool, String?, (() -> Void)?) {
        if name == "login" {
            if self.accountField.text?.count == 0 {
                return (false,"请输入账号",nil)
            }
            
            if (self.passField.text?.count)! < 6 || (self.passField.text?.count)! > 20 {
                return (false,"请输入6到20位密码",nil)
            }
        }
        
        return (true,nil,nil)
    }
    
    override func success(for name: String) -> NetSuccess {
        if name == "login" {
            func success(_ json: JSON)->Void{
                
                if json.contents?["success"] == true {
//                    if (json.dictionary?.keys.contains("APPsweepPay") ?? false) {
//                        User.configScan(ifscan: true)
//                    }
                    self.storeInfo(with: json)
                
                } else {
                    self.showError(json.contents?["errorMsg"]?.rawString())
                    if let code = json.contents?["code"]?.int {
                        if code == 6001 {
                            
                            let forget = VCLoader.vc(with: "ForgetPass", storyboardid: "BinddingDeviceViewController") as! ForgetPassViewController
                            
                            print(forget.view)
                            
                            forget.title = "绑定设备"

                            self.push(destination: forget)
                        } else if code == 6002 {
                            let passwordManager = VCLoader.vc(with: "Main", storyboardid: "PasswordManageViewController") as! PasswordManageViewController
                            passwordManager.iflogin = true
                            passwordManager.title = "修改密码"
                            passwordManager.phone = self.accountField.text ?? ""
                            self.push(destination: passwordManager)
                        }
                    }
                }
            }
            return success;
        } else {
            func suc(json: JSON){
                if let success = json.contents?["success"]?.rawValue as? Bool {
                    if success == false {
                        return
                    }
                }
                
                if let data = json.contents?["data"] {
                    let worktype = data.contents?["workType"]?.rawString() ?? ""
                    User.configRole(role: worktype)
                    
                    if let nm = data.contents?["name"]?.rawString() {
                        User.configName(name: nm)
                    }
                    
                    if let account = data.contents?["account"]?.rawString() {
                        User.configAccount(account: account)
                    }
                    
                    if let id = data.contents?["id"]?.rawString() {
                        User.configId(id: id)
                    }
                    
                    if let phe = data.contents?["phone"]?.rawString() {
                        User.configPhone(phone: phe)
                    }
                    if let code = data.contents?["orgCode"]?.rawString() {
                        User.configOrgCode(orgCode: code)
                    }
                    if let admin = data.contents?["admin"]?.int {
                        if admin == 1 {
                            User.configIfAdmin(ifadmin: true)
                        } else {
                            User.configIfAdmin(ifadmin: false)
                        }
                    } else {
                        User.configIfAdmin(ifadmin: false)
                    }
                    
                    let animation = CATransition.init()
                    
                    animation.type = CATransitionType.fade
                    
                    JPUSHService.setAlias(User.id, completion: { (code, str, code1) in
                        
                    }, seq: 1)
                    
                    let story = UIStoryboard(name: "Main", bundle: Bundle.main)
                    
                    let rootVC = story.instantiateInitialViewController()
                    
                    UIApplication.shared.delegate?.window??.rootViewController = rootVC
                    
                    NotificationCenter.default.post(Notification.init(name: Notification.Name(rawValue: "UserInfoReady")))
                }
            }
            
            return suc
        }
    }
    
    override func method(for name: String) -> NetMethod {
        if name == "login" {
            return .post
        }
        return .get
    }
    
    
    func storeInfo(with json: JSON) -> Void {
        self.load(with: "userinfo")
    }
    
    @IBAction func forgetPassAction(_ sender: UIButton) {
        
        let forget = VCLoader.vc(with: "ForgetPass", storyboardid: "ForgetPassViewController")
        
        self.push(destination: forget!)
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        
       self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let account = User.account
        if account.count != 0 {
            self.accountField.text = account
        }
        self.update()
//        Timer.scheduledTimer(timeInterval: TimeInterval.init(5), target: self, selector: #selector(update), userInfo: nil, repeats: true)
        // Do any additional setup after loading the view.
    }
    
    
    @objc func update(){
        if self.presentedViewController == nil {
            let task = URLSession.shared.dataTask(with: URL.init(string: "https://tms.hyit.com.cn/tasktracking/manifest.plist")!) { (data, response, error) in
                if error == nil {
                    do {
                        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/updater.plist"
                        try data?.write(to: URL.init(fileURLWithPath: path))
                        if let dictionary = NSDictionary.init(contentsOf: URL.init(fileURLWithPath: path)) {
                            let items = JSON(dictionary)
                            let versionstr = items["items"][0]["metadata"]["bundle-version"].string ?? "0.0"
                            let version = Double.init(versionstr) ?? 0.0
                            let infoDictionary = Bundle.main.infoDictionary
                            let currentversionstr = infoDictionary?["CFBundleShortVersionString"] as! String
                            let currentversion = Double.init(currentversionstr) ?? 1.0
                            if currentversion < version {
                                DispatchQueue.main.async {
                                    let alert = UIAlertController.init(title: "发现新的版本", message: "请点击更新", preferredStyle: .alert)
                                    let action1 = UIAlertAction.init(title: "确定", style: .default, handler: { (_) in
                                        UIApplication.shared.openURL(URL.init(string: "itms-services://?action=download-manifest&url=https://tms.hyit.com.cn/tasktracking/manifest.plist")!)
                                    })
                                    alert.addAction(action1)
                                    JumpHelper.shared.topmost?.present(alert, animated: true, completion: nil)
                                }
                            }
                        }
                    } catch {
                        print(error)
                    }
                }
            }
            task.resume()
        }
    }
    
//    func currentvc() -> UIViewController {
//        var window = UIApplication.shared.keyWindow
//        if window?.windowLevel != UIWindow.Level.normal {
//            let windows = UIApplication.shared.windows
//            for tmpWin in windows {
//                if tmpWin.windowLevel == UIWindow.Level.normal {
//                    window = tmpWin
//                    break
//                }
//            }
//        }
//        let view = window?.subviews.first
//        let responder = view?.next
//        if responder is UIViewController {
//            return responder as! UIViewController
//        } else {
//            return window!.rootViewController!
//        }
//    }
    
//    - (UIViewController *)getCurrentVC
//    {
//    UIViewController *result = nil;
//
//    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
//    if (window.windowLevel != UIWindowLevelNormal)
//    {
//    NSArray *windows = [[UIApplication sharedApplication] windows];
//    for(UIWindow * tmpWin in windows)
//    {
//    if (tmpWin.windowLevel == UIWindowLevelNormal)
//    {
//    window = tmpWin;
//    break;
//    }
//    }
//    }
    
//    UIView *frontView = [[window subviews] objectAtIndex:0];
//    id nextResponder = [frontView nextResponder];
//
//    if ([nextResponder isKindOfClass:[UIViewController class]])
//    result = nextResponder;
//    else
//    result = window.rootViewController;
//
//    return result;
//    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
